package com.lmf.handler;

import com.lmf.exception.AgeException;
import com.lmf.exception.NameException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

//定义全局变量，用于处理全局异常
@ControllerAdvice
public class GlobalException {

    //处理NameException特定异常的方法
    @ExceptionHandler(value = NameException.class)
    public ModelAndView doNameException(Exception exception){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","姓名必须是zs，其他用户不能访问");
        mv.addObject("ex",exception);
        mv.setViewName("nameError");
        return mv;
    }

    //处理AgeException特定异常
    @ExceptionHandler(value = AgeException.class)
    public ModelAndView doAgeException(Exception exception){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","年龄必须小于80岁，且不能为空");
        mv.addObject("ex",exception);
        mv.setViewName("ageError");
        return mv;
    }

    //处理除开（AgeException，NameException）外，其他任何类型的异常
    @ExceptionHandler()
    public ModelAndView doOtherException(Exception exception){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg","存在其他异常");
        mv.addObject("ex",exception);
        mv.setViewName("otherError");
        return mv;
    }
}
